package com.pig.graduate.service.impl.produce;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pig.graduate.common.exception.MyException;
import com.pig.graduate.domain.event.EventEntry;
import com.pig.graduate.domain.event.EventExit;
import com.pig.graduate.domain.event.EventTransferDormitory;
import com.pig.graduate.domain.finance.FinanceInfo;
import com.pig.graduate.domain.produce.ProduceBoar;
import com.pig.graduate.domain.produce.ProducePig;
import com.pig.graduate.domain.sys.SysRole;
import com.pig.graduate.mapper.event.EventEntryMapper;
import com.pig.graduate.mapper.event.EventExitMapper;
import com.pig.graduate.mapper.event.EventTransferDormitoryMapper;
import com.pig.graduate.mapper.finance.FinanceInfoMapper;
import com.pig.graduate.mapper.produce.ProducePigMapper;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.produce.ProducePigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * (ProducePig)表服务实现类
 *
 * @author makejava
 * @since 2023-03-13 16:32:28
 */
@Service("producePigService")
public class ProducePigServiceImpl extends ServiceImpl<ProducePigMapper, ProducePig> implements ProducePigService {

    @Autowired
    private EventEntryMapper eventEntryMapper;

    @Autowired
    private ProducePigMapper producePigMapper;

    @Autowired
    private EventTransferDormitoryMapper eventTransferDormitoryMapper;

    @Autowired
    private EventExitMapper eventExitMapper;

    @Autowired
    private FinanceInfoMapper financeInfoMapper;


    @Override
    public MyResult pigList(ProducePig producePig) {
        PageHelper.startPage(producePig.getPageNum(),producePig.getPageSize());
        List<ProducePig> list = producePigMapper.pigList(producePig);
        for(int i = 0; i < list.size(); i++){
            if(list.get(i).getBirthDate() != null){
                long betweenDay = DateUtil.between(list.get(i).getBirthDate(), new Date(), DateUnit.DAY);
                list.get(i).setAverageDayAge(String.valueOf(betweenDay));
            }
            list.get(i).setLocation(list.get(i).getBuildingsName()+"-"+list.get(i).getColumnName());
        }
        PageInfo<ProducePig> pageInfo = new PageInfo<>(list);
        return MyResult.success(pageInfo);
    }

    /**
     * 肉猪进场
     * @param eventEntry
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public MyResult pigEntry(EventEntry eventEntry) {
        ProducePig pig = producePigMapper.selectOne(new QueryWrapper<ProducePig>().eq("herds_pigs_code",eventEntry.getHerdsPigsCode()).eq("is_present","在场"));
        if(pig == null){
            ProducePig producePig = new ProducePig();
            producePig.setBuildingsId(eventEntry.getBuildingsId());
            producePig.setHerdsPigsCode(eventEntry.getHerdsPigsCode());
            producePig.setPigNumber(eventEntry.getNumber());
            producePig.setCreateTime(new Date());
            producePig.setRemark(eventEntry.getRemark());
            producePig.setColumnId(eventEntry.getColumnId()); //所在位置
            producePig.setIsPresent("在场"); //在场
            producePig.setBirthDate(eventEntry.getBirthDate());
            producePigMapper.insert(producePig);
        }else{
            if(!pig.getColumnId().equals(eventEntry.getColumnId())){
                throw new MyException("该猪群已存在");
            }
            pig.setPigNumber(pig.getPigNumber() + eventEntry.getNumber());
            producePigMapper.updateById(pig);
        }
        eventEntry.setEntryPigType(1); //肉猪
        eventEntryMapper.insert(eventEntry);
        //财务数据录入
        FinanceInfo financeInfo = new FinanceInfo();
        financeInfo.setCreateTime(new Date());
        financeInfo.setNumber(eventEntry.getNumber());
        financeInfo.setName("肉猪购买成本");
        financeInfo.setSummary("猪只购买 群号："+eventEntry.getHerdsPigsCode());
        financeInfo.setDataType("猪只购买");
        financeInfo.setIncomeExpensesType("支出");
        financeInfo.setTotalPrice(eventEntry.getPrice().multiply(new BigDecimal(-1))); //这是总价
        BigDecimal price = eventEntry.getPrice().divide(new BigDecimal(eventEntry.getNumber()),2, RoundingMode.HALF_UP);
        financeInfo.setPrice(price.multiply(new BigDecimal(-1)));
        financeInfoMapper.insert(financeInfo);


        return MyResult.success("进场成功");
    }

    /**
     * 肉猪转场
     * @param eventTransferDormitory
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public MyResult pigMoveBuildings(EventTransferDormitory eventTransferDormitory) {
        ProducePig producePigOut = producePigMapper.selectOne(new QueryWrapper<ProducePig>().eq("herds_pigs_code",eventTransferDormitory.getHerdsPigsCodeOut()).eq("is_present","在场"));
        if(producePigOut.getPigNumber() < eventTransferDormitory.getNumber()){
            throw new MyException("转出的数量大于转出猪群的总数量!!");
        }
        //可以转入新群 也可以转入已有的群
        //查找转入群
        ProducePig producePigIn = producePigMapper.selectOne(new QueryWrapper<ProducePig>().eq("herds_pigs_code",eventTransferDormitory.getHerdsPigsCodeIn()).eq("is_present","在场"));
        if(producePigIn == null){//转入群为新群
            producePigIn = new ProducePig();
            producePigIn.setHerdsPigsCode(eventTransferDormitory.getHerdsPigsCodeIn());
            producePigIn.setPigNumber(eventTransferDormitory.getNumber());
            producePigIn.setCreateTime(new Date());
            producePigIn.setRemark(eventTransferDormitory.getRemark());
            producePigIn.setColumnId(eventTransferDormitory.getColumnIn()); //所在位置
            producePigIn.setBirthDate(producePigOut.getBirthDate());
            producePigIn.setIsPresent("在场"); //在场
            producePigMapper.insert(producePigIn);
        }else{ //转入老群
            producePigIn.setPigNumber(producePigIn.getPigNumber() + eventTransferDormitory.getNumber());
            producePigMapper.updateById(producePigIn);
        }
        producePigOut.setPigNumber(producePigOut.getPigNumber() - eventTransferDormitory.getNumber());
        producePigMapper.updateById(producePigOut);
        eventTransferDormitory.setTdPigType(1);
        eventTransferDormitoryMapper.insert(eventTransferDormitory);
        return MyResult.success("转舍成功");
    }

    /**
     * 肉猪离场
     * @param eventExit
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public MyResult pigLeave(EventExit eventExit) {
        ProducePig producePig = producePigMapper.selectOne(new QueryWrapper<ProducePig>().eq("herds_pigs_code",eventExit.getHerdsPigsCode()).eq("is_present","在场"));
        ProducePig producePigOut = producePigMapper.selectOne(new QueryWrapper<ProducePig>().eq("herds_pigs_code",eventExit.getHerdsPigsCode()).eq("is_present","离场"));
        if(producePig.getPigNumber() < eventExit.getNumber()){
            throw new MyException("离场数量大于猪群数量");
        }else if (producePig.getPigNumber() > eventExit.getNumber()){
            producePig.setPigNumber(producePig.getPigNumber()-eventExit.getNumber());
            if(producePigOut == null){
                ProducePig p = new ProducePig();
                BeanUtils.copyProperties(producePig, p);
                p.setPigNumber(eventExit.getNumber());
                p.setId(null);
                p.setIsPresent("离场");
                producePigMapper.insert(p);
            }else{
                producePigOut.setPigNumber(producePigOut.getPigNumber() + eventExit.getNumber());
                producePigMapper.updateById(producePigOut);
            }
        }else if(producePig.getPigNumber().equals(eventExit.getNumber())){
            producePig.setIsPresent("离场");
        }
        producePigMapper.updateById(producePig);
        eventExit.setExitPigType(1);
        eventExitMapper.insert(eventExit);
        FinanceInfo financeInfo = new FinanceInfo();
        financeInfo.setCreateTime(new Date());
        financeInfo.setNumber(eventExit.getNumber());
        financeInfo.setPrice(eventExit.getUnitPrice());
        financeInfo.setTotalPrice(eventExit.getPrice());
        financeInfo.setName("猪只销售收入");
        financeInfo.setSummary("猪只销售 群号："+eventExit.getHerdsPigsCode());
        financeInfo.setDataType("猪只销售");
        financeInfo.setIncomeExpensesType("收入");
        financeInfoMapper.insert(financeInfo);
        return MyResult.success("离场成功");
    }
}

